package com.hrs.core.service.impl;

import com.hrs.enity.vo.PositionVo;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 摆渡人
 * @description
 * @date 2023/1/12 23:58
 */
@Service
public class PositionTreeService {

    public List<PositionVo> buildPositionTree(List<PositionVo> positionVoList) {
        if(CollectionUtils.isEmpty(positionVoList)) {
            return new ArrayList<PositionVo>();
        }
        List<PositionVo> positionVos =
                positionVoList.stream().filter(e -> e.getParentId() == null || e.getParentId() == 0).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(positionVoList)) {
            return new ArrayList<PositionVo>();
        }
        this.buildPositionTree(positionVos,positionVoList);
        return positionVos;
    }

    public void buildPositionTree(List<PositionVo> nodeList,List<PositionVo> positionVoList) {
        int nodeSize = nodeList.size();
        for(int i = 0; i < nodeSize; i ++) {
            int preIndex = i - 1;
            int nextIndex = i + 1;
            PositionVo node = nodeList.get(i);
            if(preIndex > -1) {
                node.setPreId(nodeList.get(preIndex).getId());
            }
            if(nextIndex < nodeSize) {
                node.setNextId(nodeList.get(nextIndex).getId());
            }
            buildPositionTree(node,positionVoList);
        }
    }

    public void buildPositionTree(PositionVo node,List<PositionVo> positionVoList) {
        List<PositionVo> children = getChildren(node, positionVoList);
        if(!CollectionUtils.isEmpty(children)) {
            node.setChildrenPosition(children);
            this.buildPositionTree(children,positionVoList);
        }

    }

    private List<PositionVo> getChildren(PositionVo node,List<PositionVo> positionVoList) {
        Long id = node.getId();
        return positionVoList.stream().filter(e -> id.equals(e.getParentId())).collect(Collectors.toList());

    }
}
